﻿
package com.ostrich.manpower.controller;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.base.util.DateUtil;
import com.base.util.HtmlUtil;
import com.base.util.SessionUtils;
import com.base.web.BaseAction;
import com.ostrich.manpower.bean.TostHrBaseinfo;
import com.ostrich.manpower.bean.TostHrCheckinlog;
import com.ostrich.manpower.common.ImportUtil;
import com.ostrich.manpower.common.OstDateUtils;
import com.ostrich.manpower.service.impl.TostHrBaseinfoService;
import com.ostrich.manpower.service.impl.TostHrCheckinlogService;
import com.ostrich.system.analysis.ParaminfoUtil;
import com.ostrich.system.bean.TostSysParaminfo;

/**
 * ClassName: Controller <br/>
 * date: 2013-5-9 下午03:07:38 <br/>
 * 
 * @author wangyinan
 * @version
 */
@Controller
@RequestMapping("/tostHrCheckinlog")
public class TostHrCheckinlogController extends BaseAction
{
	private final static Logger log= Logger.getLogger(TostHrCheckinlogController.class);

	// Servrice start
	@Autowired(required=false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private TostHrCheckinlogService<TostHrCheckinlog> tostHrCheckinlogService; 
	@Autowired(required=false)
	private TostHrBaseinfoService<TostHrBaseinfo> tosthrbaseinfoservice;
	/**
	 * ilook 首页
	 * @param url
	 * @param classifyId
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView  list(TostHrCheckinlog tostHrCheckinlog,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		List<TostHrCheckinlog> dataList = tostHrCheckinlogService.queryByList(tostHrCheckinlog);
		//设置页面数据
		context.put("dataList", dataList);
		return forword("manpower/tabTostHrCheckinlog",context);
	}
	
	/**
	 * json 列表页面
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/dataList")
	public void  dataList(TostHrCheckinlog tostHrCheckinlog,HttpServletResponse response) throws Exception{
		List<TostHrCheckinlog> dataList = tostHrCheckinlogService.queryByList(tostHrCheckinlog);
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",tostHrCheckinlog.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}


	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/save")
	public void save(HttpServletRequest request,TostHrCheckinlog bean,HttpServletResponse response) throws Exception{
		
		if(bean.getId()==null){
			bean.setHciMonth(OstDateUtils.getDateByMonth(bean.getHciMonth()));
			TostHrBaseinfo bsinfo= (TostHrBaseinfo) tosthrbaseinfoservice.queryById(bean.getHrId());
			bean.setHrId(bsinfo.getId());
			bean.setHrName(bsinfo.getHrName());
			
			//查询改用的该类型该月份 有数据
			TostHrCheckinlog cklg= tostHrCheckinlogService.queryChenckLog(bean);
			if(cklg!=null && cklg.getId()!=null){
				bean.setId(cklg.getId());
				tostHrCheckinlogService.updateCheck(bean);
				sendSuccessMessage(response, bean.getHrName()+"的"+bean.getHciMonth()+"月份数据已有，请选择编辑。");
			}else{
				bean.setCreatetime(DateUtil.getNowPlusTime());
				bean.setPerson(SessionUtils.getUser(request).getEmail());
				tostHrCheckinlogService.addCheck(bean);
				sendSuccessMessage(response, "保存成功~");
			}
			
		}else{
			tostHrCheckinlogService.updateCheck(bean);
			sendSuccessMessage(response, "保存成功~");
		}
		
//		if(bean.getId()==null){
//			tostHrCheckinlogService.addCheck(bean);
//		}else{
//			tostHrCheckinlogService.updateCheck(bean);
//		}
	}
	
	@RequestMapping("/getId")
	public void getId(Integer id,HttpServletResponse response) throws Exception{
		Map<String,Object>  context = getRootMap();
		TostHrCheckinlog bean  = tostHrCheckinlogService.queryById(id);
		if(bean  == null){
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}
	
	@RequestMapping("/delete")
	public void delete(Integer[] id,HttpServletResponse response) throws Exception{
		tostHrCheckinlogService.delete(id);
		sendSuccessMessage(response, "删除成功");
	}
	
	@RequestMapping("getCheckType")
	public void getCheckType(HttpServletResponse response){
		Map<Integer, TostSysParaminfo> cmps = ParaminfoUtil.getParamByPid(50);
		List<TostSysParaminfo> ls = new ArrayList<TostSysParaminfo>();
		for(Map.Entry<Integer, TostSysParaminfo> cp:cmps.entrySet()){
			ls.add(cp.getValue());
		}
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",(ls!=null)?ls.size():0);
		jsonMap.put("data", ls);
		HtmlUtil.writerJson(response, jsonMap);
	}
	
	@RequestMapping(value="/upload",method = RequestMethod.POST)
	public ModelAndView imports(HttpServletRequest request,HttpServletResponse respne,ModelMap map){
		MultipartHttpServletRequest muirequest=(MultipartHttpServletRequest)request;
		MultipartFile mfile=muirequest.getFile("xlsfile");
		String filepath=request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
		String filename=mfile.getOriginalFilename();
		
		try{
			InputStream is=mfile.getInputStream();
			byte [] b=new byte[1048576];
			int length=is.read(b);
			filepath+="\\"+filename;
			FileOutputStream fos=new FileOutputStream(filepath);
			fos.write(b, 0,length);
			is.close();
			fos.close();
			request.setAttribute("path",filepath);
			request.setAttribute("month", request.getParameter("hciMonth"));
		}catch(Exception e){System.out.println("filepath");
		
		}
		return new ModelAndView("forward:/tostHrCheckinlog/upimport.do");
	}
	
	@RequestMapping(value = "/upimport")
	public ModelAndView upimport(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> context = getRootMap();
		String filepath = (String)request.getAttribute("path");
		String month = (String) request.getAttribute("month");
		try{
			InputStream fis = new FileInputStream(filepath);
			HSSFSheet sh = ImportUtil.getSheet(fis);
			String times12 = month.substring(0,4);
			String times11 = month.substring(5,7);
			String hs = times12 + times11;
			String msg = tostHrCheckinlogService.checklogBySheet(hs, sh,request);
			msg=(msg!=null && msg.trim().length()>0)?"您已经成功导入。但是还有："+msg:"您已经导入成功请查看。";
			request.setAttribute("msg",msg );
		}catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "导入失败，请查看xls文件是否模板正确");
		}
		request.setAttribute("url", request.getContextPath()
				+ "/tostHrCheckinlog/list.do");
		return forword("penmsg2", context);
	}
}
